package com.fz.controller;

import cn.hutool.core.collection.CollUtil;
import com.fz.common.Result;
import com.fz.controller.request.AdminPageRequest;
import com.fz.controller.request.CategoryPageRequest;
import com.fz.pojo.Category;
import com.fz.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/category")
@CrossOrigin
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    //查询用户
    @GetMapping("/list")
    public Result list() {
        List<Category> category = categoryService.list();
        return Result.success(category);
    }

    @GetMapping("/tree")
    public Result tree() {
        List<Category> category = categoryService.list();

        //对list进行操作
        //比如 递归实现 children列表的查询
        return Result.success(creatTree(null,category));// null表示从第一级开始递归
    }
    //完全递归的方法来实现递归树
    private List<Category> creatTree(Integer pid,List<Category> categories){
        ArrayList<Category> treeList = new ArrayList<>();
        for (Category category : categories) {
            if (pid==null){
                if (category.getPid()==null){//那这就是第一级节点
                    treeList.add(category);
                    category.setChildren(creatTree(category.getId(),categories));
                }
            }else {
                if (pid.equals(category.getPid())){
                    treeList.add(category);
                    category.setChildren(creatTree(category.getId(),categories));
                }
            }
            if (CollUtil.isEmpty(category.getChildren())){
                category.setChildren(null);
            }
        }
        return  treeList;
    }

    //通过id查询种类
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Category category = categoryService.getById(id);
        return Result.success(category);
    }

    //分页
    @GetMapping("/page")
    public Result page(CategoryPageRequest categoryPageRequest) {
        return Result.success(categoryService.page(categoryPageRequest));
    }


    // 添加
    @PostMapping("/addCategory")
    public Result addCategory(@RequestBody Category category) {//这里要加@RequestBody 如果不加添加都是null
        categoryService.addCategory(category);
        return Result.success();
    }

    //更新
    @PutMapping("/update")
    public Result update(@RequestBody Category category) {
        categoryService.update(category);
        return Result.success();
    }

    //删除
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        categoryService.deleteById(id);
        return Result.success();
    }
    


}
